import React from 'react'
import {connect} from 'react-redux'
import action from '../store/action/index'
import { Form, Modal, Table, Input,  Spin, Radio, Tag, Divider, Button } from 'antd';
import {Link} from 'react-router-dom';
import {genProjectApi, fetchPageProjectApi, addProjectApi, modifyProjectApi} from '../api/projectManager';
import {message} from "antd/lib/index";

const FormItem = Form.Item;

class ProjectManager extends React.Component {

    state = {
        visible: false,
        loading: false,
        projectList: [],
        projectInfo: {}
    }

    genProjectId;

    constructor(props, context) {
        super(props, context);
    }

    componentDidMount() {
        document.title = '项目管理';
        this.loadPageProjectList(1);
    }

    loadPageProjectList(page) {
        var ret = fetchPageProjectApi(page, 22);
        ret.then((res)=>{
            this.setState({...this.state, projectList: res.data.data});
        })
    }

    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
            }
        });
    }

    showProjectInfo(pInfo){
        console.info(JSON.stringify(pInfo));
        this.setState({...this.state, projectInfo: pInfo, visible: true})
    }

    saveProjectInfo() {
        let that = this;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);

                let {id} = that.state.projectInfo;


                let formData = that.props.form.getFieldsValue();

                let ret = null;
                if( id ) {
                    formData.id = id;
                    ret = modifyProjectApi(formData);
                } else {
                    ret = addProjectApi(formData);
                }

                ret.then((res)=>{
                    message.success('保存成功！');
                    that.setState({...that.state, projectInfo: {}, visible: false})
                    that.loadPageProjectList(1)
                });
            }
        });
    }

    render() {

        let { projectList } = this.state;
        const proTypeDic = {simple:'单应用', micro:'微服务'};
        const rows = projectList.rows;

        // <Link to={{ pathname:'/projectConfig', search: `?projectId=${record.id}` }} target="_blank"></Link>

        const columns = [{
            title: 'Name',
            dataIndex: 'name',
            key: 'name',
            render: (text, record) => (
                <span>
                    <a href={`#/projectConfig?projectId=${record.id}`} target="_blank">{text}</a>
                </span>
            ),
        }, {
            title: '服务类型',
            key: 'proType',
            dataIndex: 'proType',
            render: text => <Tag color={text==='simple'?'blue':'green'} key={text}>{proTypeDic[text]}</Tag>,

        },{
            title: '是否生成WebUi',
            key: 'genWeb',
            dataIndex: 'genWeb',
            render: text => <Tag color={text==='no'?'blue':'green'} key={text}>{text}</Tag>,

        }, {
            title: 'ArtifactId',
            dataIndex: 'artifactId',
            key: 'artifactId',
        }, {
            title: 'GroupId',
            dataIndex: 'groupId',
            key: 'groupId',
        }, {
            title: 'version',
            key: 'version',
            dataIndex: 'version',
            render: text => <Tag color="blue" key={text}>{text}</Tag>,

        }, {
            title: 'Action',
            key: 'action',
            render: (text, record) => (
                <span>
                    <a href="javascript:;" onClick={()=>{
                        this.showProjectInfo(record)
                    }}>修改</a>
                    <Divider type="vertical" />
                    <a href="javascript:;" onClick={()=>{

                        this.genProjectId = record.id;


                        var localPath = localStorage.getItem('genProjectLocalPath_' + this.genProjectId);


                        if( ! localPath) {
                            localPath = record.localPath;
                        }

                        this.setState({...this.state, genVisible: true, genProjectLocalPath: localPath, proType: record.proType})

                    }}>生成</a>
                    <Divider type="vertical" />
                    <a href="javascript:;">删除</a>
                </span>
            ),
        }];

        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                sm: { span:  6},
            },
            wrapperCol: {
                sm: { span: 18 },
            },
        };


        return <div>

            <Button type="primary" icon="plus" onClick={()=>{ this.showProjectInfo({}); }}> 添加项目 </Button>

            <Spin spinning={this.state.loading} delay={500}>

            {/* 项目列表 */}
            <Table columns={columns} rowKey={record => record.id} dataSource={rows} />

            </Spin>
            {/* 项目详情 */}
            <Modal
                width={800}
                title="项目详情"
                maskClosable={false}
                visible={this.state.visible}
                okText={"保存项目"}
                onOk={()=>{
                    this.saveProjectInfo();
                }}
                cancelText={"关闭"}
                onCancel={()=>{
                    this.setState({...this.state, visible: false})
                }}
            >
                <Form className={"form_item_4 form_row_small_margin"} onSubmit={this.handleSubmit}>
                    <FormItem
                        {...formItemLayout}
                        label="项目名称" >
                        {getFieldDecorator('name', {
                            initialValue: this.state.projectInfo.name,
                            rules: [{ required: true, message: '不可为空' }],
                        })(
                            <Input className={"ant-col-12"} />
                        )}
                        <span className="ant-form-text"> 项目名称(英文字母) </span>
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="项目介绍" >
                        {getFieldDecorator('description', {
                            initialValue: this.state.projectInfo.description,
                            rules: [{ required: true, message: '不可为空' }],
                        })(
                            <Input className={"ant-col-12"} />
                        )}
                        <span className="ant-form-text"> 项目介绍 </span>
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="groupId" >
                        {getFieldDecorator('groupId', {
                            initialValue: this.state.projectInfo.groupId,
                            rules: [{ required: true, message: '不可为空' }],
                        })(
                            <Input className={"ant-col-12"} />
                        )}
                        <span className="ant-form-text"> com.test </span>
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="artifactId" >
                        {getFieldDecorator('artifactId', {
                            initialValue: this.state.projectInfo.artifactId,
                            rules: [{ required: true, message: '不可为空' }],
                        })(
                            <Input className={"ant-col-12"} />
                        )}
                        <span className="ant-form-text"> test_rest </span>
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="生成WebUi" >
                        {getFieldDecorator('genWeb', {
                            initialValue: this.state.projectInfo.genWeb,
                            rules: [{ required: true, message: '不可为空' }],
                        })(
                            <Radio.Group className="ant-col-12">
                                <Radio value="no">no</Radio>
                                <Radio value="yes">yes</Radio>
                            </Radio.Group>
                        )}
                        <span className="ant-form-text"> * 生成WebUi选项不可为空</span>
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="结构" >
                        {getFieldDecorator('packageType', {
                            initialValue: this.state.projectInfo.packageType,
                            rules: [{ required: true, message: '不可为空' }],
                        })(
                            <Radio.Group className="ant-col-12" disabled={this.state.projectInfo.id} >
                                <Radio value="standard">standard</Radio>
                                <Radio value="module">module</Radio>
                            </Radio.Group>
                        )}
                        <span className="ant-form-text"> * 结构不可为空</span>
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="项目类型" >
                        {getFieldDecorator('proType', {
                            initialValue: this.state.projectInfo.proType,
                            rules: [{ required: true, message: '不可为空' }],
                        })(
                            <Radio.Group className="ant-col-12" disabled={this.state.projectInfo.id}>
                                <Radio value="micro">微服务</Radio>
                                <Radio value="simple">单应用</Radio>
                            </Radio.Group>
                        )}
                        <span className="ant-form-text"> * 项目类型不可为空</span>
                    </FormItem>


                    <FormItem
                        {...formItemLayout}
                        label="项目版本" >
                        {getFieldDecorator('version', {
                            initialValue: this.state.projectInfo.version,
                            rules: [{ required: true, message: '不可为空' }],
                        })(
                            <Input className={"ant-col-12"} />
                        )}
                        <span className="ant-form-text"> 项目版本 </span>
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="访问路径" >
                        {getFieldDecorator('contextPath', {
                            initialValue: this.state.projectInfo.contextPath,
                            rules: [{ required: true, message: '不可为空' }],
                        })(
                            <Input className={"ant-col-12"} />
                        )}
                        <span className="ant-form-text"> 访问路径 </span>
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="本地路径" >
                        {getFieldDecorator('localPath', {
                            initialValue: this.state.projectInfo.localPath,
                            rules: [{ required: true, message: '不可为空' }],
                        })(
                            <Input className={"ant-col-12"} />
                        )}
                        <span className="ant-form-text"> 生成项目本地路径 </span>
                    </FormItem>

                </Form>
            </Modal>


            {/* 生成地址 */}
            <Modal
                title="生成项目-地址"
                visible={this.state.genVisible}
                okText="确定生成"
                cancelText="关闭"
                width={800}
                onOk={()=>{

                    localStorage.setItem('genProjectLocalPath_' + this.genProjectId, this.state.genProjectLocalPath);
                    this.setState({...this.state, loading: true, genVisible: false});
                    const {genProjectLocalPath, proType} = this.state;
                    genProjectApi({id: this.genProjectId, localPath: genProjectLocalPath, proType: proType}).then(res=>{
                        this.setState({...this.state, loading: false});
                    })

                }}
                onCancel={ ()=>{ this.setState({...this.state, genVisible: false})}}
            >
                <Input value={this.state.genProjectLocalPath} onChange={(e)=>{
                    e.persist();
                    this.setState({...this.state, genProjectLocalPath: e.target.value});
                }} />
                <br />
            </Modal>
        </div>
    }
}

// 表单控制
const _ProjectManager = Form.create()(ProjectManager);

export default connect(state => ({...state.projectManager}), action.projectManager)(_ProjectManager);
